﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NT40Redis1.Models;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.AspNetCore.Http;

namespace NT40Redis1.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //向Session中保存数据
            HttpContext.Session.SetString("mysession", $"你好！张三{DateTime.Now}");
            ViewBag.Msg = "向Session中保存数据成功";



            //使用Redis
            //RedisCacheOptions options = new RedisCacheOptions();
            //options.Configuration = "127.0.0.1:6379";
            //options.InstanceName = "myredis";

            //var redisClient = new RedisCache(options);

            ////写入数据
            //redisClient.SetString("name", $"张三！{DateTime.Now}");
            ////指定缓存时间的写入
            ////设置绝对过期时间
            //redisClient.SetString("name1", $"张三1！{DateTime.Now}",
            //    new DistributedCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(2)));
            ////设置相对过期时间
            //redisClient.SetString("name2", $"张三2！{DateTime.Now}",
            //    new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(2)));
            //ViewBag.Msg = "数据缓存成功";
            return View();
        }

        public IActionResult Privacy()
        {
            //读取Session
            var result = HttpContext.Session.GetString("mysession");
            ViewBag.Msg = $"数据读取成功：{result}";


            //读取Redis
            //RedisCacheOptions options = new RedisCacheOptions();
            //options.Configuration = "127.0.0.1:6379";
            //options.InstanceName = "myredis";

            //var redisClient = new RedisCache(options);

            ////读取数据
            //string result=redisClient.GetString("name");
            //string result1 = redisClient.GetString("name1");
            //string result2 = redisClient.GetString("name2");
            //ViewBag.Msg = $"数据读取成功：{result} ,{result1},{result2}";
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
